package com.lock;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 多个线程，读取相同对象——多个线程，分类
 */
public class DataLockReadwrite {
    boolean hasdata;
    int x;
    ReentrantReadWriteLock lock=new ReentrantReadWriteLock();
    //Condition condition=lock.newCondition();
    public void write()
    {


            //有数据
/*            if (hasdata==true)
            {
                try {
                    condition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }*/
            //没数据
            lock.writeLock().lock();

            System.out.println(Thread.currentThread().getName()+"准备添加++数据");
            x=(int)(Math.random()*100000);
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+"添加++数据"+x);
            //通过上述步骤有了数据，并唤醒取数据

            lock.writeLock().unlock();



    }

    public  void get()
    {


            //没有数据
/*            if (hasdata==false)
            {
                try {
                    condition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }*/
            lock.readLock().lock();

            System.out.println(Thread.currentThread().getName()+"准备读取——数据");
            //x=(int)Math.random();
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+"读取数据——为"+x);
            //通过上述步骤没有数据，并唤醒添加数据

            lock.readLock().unlock();




    }
}
